#format
Description: Format a value (calls the object's __format__
method).
def format(value, format_spec=''):
'''
Format a value using format_spec.
:param value: A variable
:param format_spec: Format specification
:return: The formatted value
'''
Example:
# Numeric formatting
print(format(3.14159, ".2f")) # Output: '3.14'
print(format(1000000, ",")) # Output: '1,000,000'
# Alignment and padding
print(format("hello", "^10")) # Output: ' hello ' (center-aligned, width 10)
print(format(42, "05d")) # Output: '00042' (zero-padded, width 5)
# Base conversion
print(format(10, "b")) # Output: '1010' (binary)
print(format(255, "x")) # Output: 'ff' (lowercase hexadecimal)
#Format Specification
format_spec ::= [options][width][grouping]["." precision][type] options ::= [[fill]align][sign]["z"]["#"]["0"] fill ::= <any character> align ::= "<" | ">" | "=" | "^" sign ::= "+" | "-" | " " width ::= digit+ grouping ::= "," | "_" precision ::= digit+ type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
#Alignment Options
Option | Description |
---|---|
< | Left-align (default for text) |
> | Right-align (default for numbers) |
= | Padding after sign but before digits |
^ | Center-align |
#Sign Options
Option | Description |
---|---|
+ | Show sign for both positive and negative numbers |
- | Show sign only for negative numbers (default) |
(space) | Leading space for positive, - for negative |
#Separator Options
Option | Description |
---|---|
, | Use comma as thousands separator |
_ | Use underscore as thousands separator |
#Integer Type Options
Option | Description |
---|---|
b | Binary |
d | Decimal |
o | Octal |
x | Hexadecimal (lowercase) |
X | Hexadecimal (uppercase) |
n | Like d , but uses locale-specific separators |
c | Convert integer to corresponding Unicode character before printing |
#Floating Point Type Options
Option | Description |
---|---|
e | Scientific notation (lowercase) |
E | Scientific notation (uppercase) |
f | Fixed-point notation (default 6 decimals) |
F | Same as f , but uses uppercase |
g | General format (lowercase) |
G | General format (uppercase) |
n | Like g , but uses locale-specific separators |
% | Percentage (multiplies by 100 and adds % ) |